package com.gingko.duominuo.network.interceptor

import com.gingko.duominuo.App
import com.gingko.duominuo.BuildConfig
import com.gingko.duominuo.data.datastore.DataStoreHelper
import com.gingko.duominuo.data.source.local.RoomModule
import com.gingko.duominuo.network.assemblyQueryParams
import kotlinx.coroutines.runBlocking
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.HashMap
import kotlin.jvm.Throws


/**
 * Describe：
 * - okHttp拦截器，用于添加公共参数
 *
 * @author bsx
 * CreateTime：2019/8/15
 */
class CommonParamsInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest: Request = chain.request()

        // 添加新的参数
        val authorizedUrlBuilder = oldRequest.url
            .newBuilder()
            .scheme(oldRequest.url.scheme)
            .host(oldRequest.url.host)
        val builder = oldRequest.newBuilder()
        builder.addHeader("apikey", BuildConfig.APP_KEY)
        runBlocking {
            if (DataStoreHelper.isLogin()) {
                val appDataBase = RoomModule.provideAppDataBase(App.instance)
                RoomModule.providerUserDao(appDataBase).queryUser(DataStoreHelper.getUserId()!!)?.let {
                    builder.addHeader("vendor", it.account ?: "dev")
                    builder.addHeader("handle", it.handle ?: "manual")
                }
            }
        }

        val httpUrl: HttpUrl = authorizedUrlBuilder.build()
        builder.method(oldRequest.method, oldRequest.body)
            .url(httpUrl)
        val newRequest: Request = builder.build()
        return chain.proceed(newRequest)
    }

    private fun getCommonParams(request: Request): Map<String, Any> {
        val url: HttpUrl = request.url
        var path: String = url.toUrl().getPath()
        if (path.startsWith("/")) {
            path = path.substring(1)
        }
        val queryParams: MutableMap<String, Any> = HashMap()
        val keys: Set<String> = url.queryParameterNames
        if (keys.isNotEmpty()) {
            for (key in keys) {
                url.queryParameter(key)?.let {
                    queryParams[key] = it
                }
            }
        }
        return assemblyQueryParams(path, queryParams)
    }
}